import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {PublicService} from '../../services/public.service';
import {EventBusService} from '../../services/event-bus.service';
import {MessageService} from 'primeng/components/common/messageservice';
import {ConfirmationService} from 'primeng/primeng';
import {BasePage} from '../../base.page';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-cap-root',
  templateUrl: './cap-root.component.html',
  styleUrls: ['./cap-root.component.scss']
})
export class CapRootComponent extends BasePage implements OnInit {
    title: string = '编辑根节点信息';
    spaceNodeObj: Object = {
        'father': '',
        'father_did': '',
        'name': '',
        'did': '',
        'sp_type': '',
        'status': '',
        'remark': '',
        'custom1': '',
        'custom2': ''
    };
    myForm: FormGroup;
    constructor(private router: Router,
                private fb: FormBuilder,
                private activedRouter: ActivatedRoute,
                private publicService: PublicService,
                private eventBusService: EventBusService,
                public messageService: MessageService,
                public confirmationService: ConfirmationService) {
      super(confirmationService, messageService);
    }

    ngOnInit() {
        this.initData();
        this.initForm();
    }

    goBack() {
        this.router.navigate(['../../capacityBasalDatas'], {relativeTo: this.activedRouter});
    }
    initData() {
        this.publicService.getSingleNode('ROOT').subscribe(res => {
            this.spaceNodeObj['name'] = res && res['name'];
            this.spaceNodeObj['did'] = res && res['did'];
        });
    }
    initForm() {
        this.myForm = this.fb.group({
            name: ''
        });
    }
    save() {
        if (this.spaceNodeObj['name']) {
            this.publicService.editSpaceNode(this.spaceNodeObj).subscribe(res => {
               if (res === '00000') {
                   this.alert('编辑成功');
                   this.eventBusService.space.next(true);
                   this.router.navigate(['../../capacityBasalDatas'], {queryParams: {did: this.spaceNodeObj['father_did']}, relativeTo: this.activedRouter});
               }else {
                   this.alert(`编辑失败: ${res}`, 'error');
               }
            });
        }else {
            this.setValidators();
            this.alert('请填写完整信息', 'warn');
        }
    }
    get name() {
        return this.myForm.controls['name'].touched && this.myForm.controls['name'].hasError('required');
    }
    setValidators() {
        this.myForm.controls['name'].setValidators([Validators.required]);
        this.myForm.controls['name'].updateValueAndValidity();
    }
}
